﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Pollogger.Library
{
    [Serializable]
    public class LogWriter
    {
        public LogWriter(Logger parentLogger)
        {
            _parentLogger = parentLogger;
        }
        private string _name;
        private string _filePathFormat;
        private string _directory;
        private Logger _parentLogger;

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        public string FilePathFormat
        {
            get { return _filePathFormat; }
            set { _filePathFormat = value; }
        }

        public string Directory
        {
            get { return _directory; }
            set { _directory = value; }
        }

        public Logger ParentLogger
        {
            get { return _parentLogger; }
            set { _parentLogger = value; }
        }

        public List<LogFile> GetFiles()
        {
            List<LogFile> files = new List<LogFile>();
            string directory = this.Directory;
            if (!System.IO.Path.IsPathRooted(directory))
            {
                directory = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(this.ParentLogger.ParentConfig.FilePath), this.Directory);
            }
            string filename = System.IO.Path.Combine(directory, GetFullFilepath(this, DateTime.Now));
            directory = System.IO.Path.GetDirectoryName(filename);
            if (System.IO.Directory.Exists(directory))
            {
                string[] filenames = System.IO.Directory.GetFiles(directory, "*" + System.IO.Path.GetExtension(filename));
                for (int i = 0; i < filenames.Length; i++)
                {
                    System.IO.FileInfo fileInfo = new System.IO.FileInfo(filenames[i]);
                    if (fileInfo.Exists && fileInfo.FullName == System.IO.Path.Combine(directory, System.IO.Path.GetFileName(GetFullFilepath(this, fileInfo.CreationTime))))
                        files.Add(new LogFile(this, fileInfo));
                }
            }
            return files;
        }

        private static string GetFullFilepath(Pollogger.Library.LogWriter writer, DateTime date)
        {
            System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo(writer.ParentLogger.ParentConfig.Configuration.Repository.CultureCode);
            string filename = string.Format(culture, PrepareFormat(writer), date);
            return filename;
        }

        private static string PrepareFormat(Pollogger.Library.LogWriter writer)
        {
            return "{0:" + writer.FilePathFormat.Replace("{", "{{").Replace("}", "}}") + "}";
        }
    }
}
